package cn.tworice.interceptor;

import cn.tworice.admin.service.SystemService;
import com.alibaba.fastjson.JSON;
import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;
import cn.tworice.common.vo.RequestResult;
import cn.tworice.common.vo.StatusCode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.Date;

/**
 * 管理系统身份验证拦截器
 * @author 二饭
 * @email 1786705138@qq.com
 */
public class AdminInterceptor implements HandlerInterceptor {

    @Autowired
    private SystemService systemService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        String origin  = request.getHeader(HttpHeaders.ORIGIN);
        if (origin != null) {
            response.setHeader("Access-Control-Allow-Origin", "*");
            response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE, PUT, HEAD");
            response.setHeader("Access-Control-Allow-Headers", "Content-Type, Token, adminID");
            response.setHeader("Access-Control-Max-Age", "3600");
        }
        try {
            String token = request.getHeader("token");
            String adminID = request.getHeader("adminID");
            if (token == null || !systemService.exist(adminID,token)) {
                returnJson(response, "请求未授权");
                return false;
            }
            // 解码
            DecodedJWT decode = JWT.decode(token);
            // 验证密钥是否正确
            Algorithm algorithm = Algorithm.HMAC256(adminID);
            algorithm.verify(decode);
            // 有效期是否超时
            Date expiresAt = decode.getExpiresAt();
            if(expiresAt.getTime()<System.currentTimeMillis()){
                returnJson(response, "Token未授权或已超时");
                return false;
            }
            return true;
        }catch (Exception ex){
            returnJson(response, "Token未授权或已超时");
        }
        return false;
    }

    /**
     * 请求被拦截后返回给客户端数据
     * @author 二饭
     * @email 1786705138@qq.com
     */
    private void returnJson(HttpServletResponse response,String message){
        PrintWriter writer = null;
        response.setCharacterEncoding("UTF-8");
        response.setContentType("text/html; charset=utf-8");
        RequestResult result = new RequestResult();
        result.setStatus(new StatusCode(401,message));
        String jsonString = JSON.toJSONString(result);
        try {
            writer = response.getWriter();
            writer.print(jsonString);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (writer != null) {
                writer.close();
            }
        }
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
